package threading;

//

public class Demo4 {
    public static void main(String[] args) {
        Object locker1 = new Object();
        Object locker2 = new Object();

        // 约定先加 小编号
        Thread t1 = new Thread(() -> {

            System.out.println("t1尝试获取locker1");
            synchronized (locker1) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("t1尝试获取locker2");
                synchronized (locker2) {
                    System.out.println("t1获取两把锁成功！");
                }
            }
        });

        // 线程t2
        // 锁是嵌套关系
        Thread t2 = new Thread(() -> {
            System.out.println("t2尝试获取locker1");
            synchronized (locker1) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("t2尝试获取locker2");
                synchronized (locker2) {
                    System.out.println("t2获取两把锁成功！");
                }
            }
        });


        // 启动线程
        t1.start();
        t2.start();

        // 运行结果：成功！

        // 注意加锁顺序！！！
    }
}
